package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.service.AnalysisCacheParamManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.TransportOperateLogManageService;
import com.hunttown.mes.rpc.domain.AnalysisCacheParamDTO;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.query.AnalysisCacheParamDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 缓存管理
 * @author: wangjunfu
 * @date: 2018-11-27 16:34:18
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/cache")
public class CacheParamController {

    private final static Logger logger = LoggerFactory.getLogger(CacheParamController.class);

    private final AnalysisCacheParamManageService cacheParamService;
    private final AnalysisManageManageService manageService;
    private final TransportOperateLogManageService logService;

    @Resource
    private Cache jedisCache;

    @Autowired
    public CacheParamController(AnalysisCacheParamManageService cacheParamService, AnalysisManageManageService manageService, TransportOperateLogManageService logService) {
        this.cacheParamService = cacheParamService;
        this.manageService = manageService;
        this.logService = logService;
    }

    // 首页
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, AnalysisCacheParamDTOQuery objDTOQuery) {

        objDTOQuery.setOrderBy("order by id desc");
        Page<AnalysisCacheParamDTO> dataPage = cacheParamService.getForPage(objDTOQuery);
        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));

        model.addAttribute("dtoQuery", objDTOQuery);

        return "basic/cache/index";
    }

    // 编辑
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = id == null ? 0 : id;

        AnalysisCacheParamDTO obj = new AnalysisCacheParamDTO();
        obj.setId(id);

        if (id > 0) {
            obj = cacheParamService.getById(id);
        }

        model.addAttribute("Obj", obj);

        return "basic/cache/edit";
    }

    // 保存 Ajax异步调用
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, AnalysisCacheParamDTO objDTO) {

        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();
        try {
            if (objDTO.getStopFlag() == null) {
                objDTO.setStopFlag(0);
            }

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                AnalysisCacheParamDTOQuery query = new AnalysisCacheParamDTOQuery();
                query.setCacheKey(objDTO.getCacheKey());
                query.setDeleteFlag(0);

                AnalysisCacheParamDTO obj = cacheParamService.getByQuery(query);
                if (obj != null && obj.getId() > 0) {
                    //说明已经有此记录了，不能插入。
                    map = OperateCode.CompositionResult(map, -10, "此缓存KEY已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setDeleteFlag(0);

                objDTO = cacheParamService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setCacheKey(null);

                Boolean isNext = cacheParamService.updateInfoById(objDTO);
                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            logService.insertSimple(1, 2, objDTO.getId(), 2,
                    "更新缓存信息",
                    FastJsonUtils.toJSONString(objDTO),
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;
        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    // 状态改变 Ajax异步
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(HttpServletRequest request, Integer id, Integer status) {
        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = cacheParamService.changeState(id, status);

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 2, id, 4,
                    "启停用缓存信息",
                    "缓存启停用：" + (isNext ? "成功" : "失败") + "：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 删除缓存
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.GET)
    public String remove(Model model, Integer id) {
        id = id == null ? 0 : id;

        AnalysisCacheParamDTO obj = new AnalysisCacheParamDTO();
        obj.setId(id);

        if (id > 0) {
            obj = cacheParamService.getById(id);
        }

        model.addAttribute("Obj", obj);

        return "basic/cache/remove";
    }

    /**
     * 删除缓存
     *
     * @param id
     * @param keys
     * @return
     */
    @RequestMapping(value = "/removeCache", method = RequestMethod.POST)
    @ResponseBody
    public String removeCache(HttpServletRequest request, Integer id, String keys) {

        //结果返回，结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            if (id == null || id <= 0) {
                map = OperateCode.CompositionResult(map, -10, "你要删除的记录不存在，请更正后再进行操作！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            if (keys == null || keys.equals("")) {
                map = OperateCode.CompositionResult(map, -10, "请输入要删除的缓存key！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            AnalysisCacheParamDTO dto = cacheParamService.getById(id);
            if (dto == null) {
                map = OperateCode.CompositionResult(map, -10, "你要删除的记录不存在，请更正后再进行操作！");
                result = JSONUtils.toJSON(map);
                return result;
            }

            keys = FormatUtils.formatCommas(keys);
            String[] key_arr = keys.split(",");
            Long removeNum = 0L;

            for (String key : key_arr) {
                if (!key.equals("")) {
                    Long r = jedisCache.delete(key);
                    removeNum += r;
                }
            }

            //region *** 更新信息完毕记录操作日志 ***
            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            logService.insertSimple(1, 2, 0, 4,
                    "删除缓存信息",
                    "缓存删除完成：" + id,
                    curr_obj.getId(),
                    IpUtils.getClientIp(request),
                    SystemUtils.getBrowserInfo(request));
            //endregion

            map = OperateCode.CompositionResult(map, 1);
            map.put("removeNums", removeNum + "");
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        AnalysisCacheParamDTO obj = new AnalysisCacheParamDTO();
        obj.setId(id);

        if (id > 0) {
            obj = cacheParamService.getById(id);
        }
        cacheParamService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion
}